﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using PTCapture.PatientInfo;
using PTCapture.Support;

namespace PTCapture.UserControls
{
    public partial class PatientControl : UserControl
    {
        #region Fields

        /// <summary>
        /// Patients.
        /// </summary>
        List<Patient> patients = new List<Patient>();

        /// <summary>
        /// Tab control this user control exists on.
        /// </summary>
        TabControl owningTabControl;

        /// <summary>
        /// Whether to allow the lbPatiens.SelectedIndex event to fire.
        /// </summary>
        bool refreshPatient = true;

        #endregion

        #region Delegates

        /// <summary>
        /// Tie to parent form to assign paths on selection
        /// </summary>
        /// <param name="videoPath"></param>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public delegate bool customHandler(string videoPath, string imagePath, string drawingPath);
        public event customHandler PatientSelected;

        #endregion

        #region Initialization

        /// <summary>
        /// Initialization
        /// </summary>
        public PatientControl()
        {
            InitializeComponent();

            lbPatients.SelectedIndexChanged += new EventHandler(lbPatients_SelectedIndexChanged);
            cbAssignedExercises.SelectedIndexChanged += new EventHandler(cbAssignedExercises_SelectedIndexChanged);
            cbExercise.SelectedIndexChanged += new EventHandler(cbExercise_SelectedIndexChanged);

            dtpFrom.ValueChanged += new EventHandler(dtpFrom_ValueChanged);
            dtpTo.ValueChanged += new EventHandler(dtpFrom_ValueChanged);

            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }

        #endregion

        #region Control Events

        /// <summary>
        /// When an exercise name is assigned to an picture.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbExercise_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Track, since we lose it in assigning the picture
            refreshPatient = false;
            int index = lbPatients.SelectedIndex;

            if (GlobalVariables.SelectedPatient != null &&
                cbAssignedExercises.SelectedIndex > -1)
            {
                GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._exerciseName = cbExercise.Text;

                SavePatientXML();
            }

            lbPatients.SelectedIndex = index;
            refreshPatient = true;
        }

        /// <summary>
        /// When a date is assigned to an exercise
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dtpFrom_ValueChanged(object sender, EventArgs e)
        {
            // Track, since we lose it in assigning the picture
            refreshPatient = false;
            int index = lbPatients.SelectedIndex;

            if (GlobalVariables.SelectedPatient != null &&
                cbAssignedExercises.SelectedIndex > -1)
            {
                patients[lbPatients.SelectedIndex].AssignedExercises[cbAssignedExercises.SelectedIndex]._startDate = dtpTo.Value;
                patients[lbPatients.SelectedIndex].AssignedExercises[cbAssignedExercises.SelectedIndex]._endDate = dtpFrom.Value;

                SavePatientXML();
            }

            lbPatients.SelectedIndex = index;
            refreshPatient = true;
        }

        /// <summary>
        /// Change selected assigned exercise
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbAssignedExercises_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Track, since we lose it in assigning the picture
            refreshPatient = false;
            int index = lbPatients.SelectedIndex;

            if (cbAssignedExercises.SelectedIndex > -1)
            {
                dtpFrom.Value = GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._startDate;
                dtpTo.Value = GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._endDate;
                cbExercise.Text = "Exercise: " + GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._exerciseName;

                if (File.Exists(GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._reason))
                {
                    pictureBox1.Load(GlobalVariables.SelectedPatient.AssignedExercises[cbAssignedExercises.SelectedIndex]._reason);
                }
                else
                {
                    MessageBox.Show("Snapshot no longer exists.", "Missing File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                dtpFrom.Enabled = true;
                dtpTo.Enabled = true;
            }
            else
            {
                dtpFrom.Enabled = false;
                dtpTo.Enabled = false;
            }

            lbPatients.SelectedIndex = index;
            refreshPatient = true;
        }

        /// <summary>
        /// Selected index changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void lbPatients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!refreshPatient)
                return;

            owningTabControl = (TabControl)this.Parent.Parent;

            if (lbPatients.SelectedIndices.Count > 0)
            {
                btnDeletePatient.Enabled = true;
                btnUpdateSelected.Enabled = true;

                owningTabControl.TabPages["tpCameras"].Enabled = true;
                owningTabControl.TabPages["tpPlayback"].Enabled = true;
                owningTabControl.TabPages["tpSnapshots"].Enabled = true;

                // Assign patient values
                txtFirstName.Text = patients[lbPatients.SelectedIndex].FirstName;
                txtLastName.Text = patients[lbPatients.SelectedIndex].LastName;
                txtAddress1.Text = patients[lbPatients.SelectedIndex].Address1;
                txtAddress2.Text = patients[lbPatients.SelectedIndex].Address2;
                txtCity.Text = patients[lbPatients.SelectedIndex].City;
                txtState.Text = patients[lbPatients.SelectedIndex].State;
                txtZIP.Text = patients[lbPatients.SelectedIndex].ZIP;
                txtPrimaryPhone.Text = patients[lbPatients.SelectedIndex].PrimaryPhone;
                txtSecondaryPhone.Text = patients[lbPatients.SelectedIndex].SecondaryPhone;

                // Create directories
                string videoPath = App.Default.RootPath + string.Format("\\{0}_{1}\\Videos", txtLastName.Text, txtFirstName.Text);
                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                string imagePath = App.Default.RootPath + string.Format("\\{0}_{1}\\Snapshots", txtLastName.Text, txtFirstName.Text);
                if (!Directory.Exists(imagePath))
                {
                    Directory.CreateDirectory(imagePath);
                }

                string drawingPath = App.Default.RootPath + string.Format("\\{0}_{1}\\Snapshots\\Drawing", txtLastName.Text, txtFirstName.Text);
                if (!Directory.Exists(drawingPath))
                {
                    Directory.CreateDirectory(drawingPath);
                }

                // Pump the message to the listener
                PatientSelected(videoPath, imagePath, drawingPath);

                // Assign for use
                GlobalVariables.SelectedPatient = patients[lbPatients.SelectedIndex];

                gbExercises.Enabled = true;
            }
            else
            {
                btnDeletePatient.Enabled = false;
                btnUpdateSelected.Enabled = false;

                owningTabControl.TabPages["tpCameras"].Enabled = false;
                owningTabControl.TabPages["tpPlayback"].Enabled = false;
                owningTabControl.TabPages["tpSnapshots"].Enabled = false;

                GlobalVariables.SelectedPatient = null;

                gbExercises.Enabled = false;
            }

            RebindAssignedExercises();
            RebindExercises();
        }

        /// <summary>
        /// Update selected patient
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateSelected_Click_1(object sender, EventArgs e)
        {
            patients[lbPatients.SelectedIndex].FirstName = txtFirstName.Text;
            patients[lbPatients.SelectedIndex].LastName = txtLastName.Text;
            patients[lbPatients.SelectedIndex].Address1 = txtAddress1.Text;
            patients[lbPatients.SelectedIndex].Address2 = txtAddress2.Text;
            patients[lbPatients.SelectedIndex].City = txtCity.Text;
            patients[lbPatients.SelectedIndex].State = txtState.Text;
            patients[lbPatients.SelectedIndex].ZIP = txtZIP.Text;
            patients[lbPatients.SelectedIndex].PrimaryPhone = txtPrimaryPhone.Text;
            patients[lbPatients.SelectedIndex].SecondaryPhone = txtSecondaryPhone.Text;

            SavePatientXML();
        }

        /// <summary>
        /// Save a new patient.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveNewPatient_Click_1(object sender, EventArgs e)
        {
            patients.Add(new Patient(txtFirstName.Text, txtLastName.Text, txtAddress1.Text, txtAddress2.Text, txtCity.Text,
                txtState.Text, txtZIP.Text, txtPrimaryPhone.Text, txtSecondaryPhone.Text));

            SavePatientXML();
        }

        /// <summary>
        /// Delete the selected patient.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeletePatient_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this patient?", "Delete?", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                patients.RemoveAt(lbPatients.SelectedIndex);

                Directory.Delete(GlobalVariables.ImagePath);
                Directory.Delete(GlobalVariables.VideoPath);
                Directory.Delete(GlobalVariables.DrawingPath);

                SavePatientXML();
            }
        }

        #endregion

        #region XML

        /// <summary>
        /// Save patient class as XML.
        /// </summary>
        public void SavePatientXML()
        {
            //patients[0].AssignedExercises.Add(new AssignedExercise(DateTime.Now, DateTime.Now, "test"));
            //patients[0].AssignedExercises = new AssignedExercise(DateTime.Now, DateTime.Now, "test");

            PatientList pl = new PatientList();
            pl.Items = patients;

            XmlSerializer serializer = new XmlSerializer(typeof(PatientList));

            using (FileStream fs = new FileStream(App.Default.RootPath + "\\Patients.xml", FileMode.Create))
            {
                serializer.Serialize(fs, pl);
            }

            RebindPatients();
        }

        /// <summary>
        /// Load existin patients from XML.
        /// </summary>
        public void LoadPatientXML()
        {
            if (File.Exists(App.Default.RootPath + "\\Patients.xml"))
            {
                PatientList pl = new PatientList();

                XmlSerializer serializer = new XmlSerializer(typeof(PatientList));

                using (FileStream fs = new FileStream(App.Default.RootPath + "\\Patients.xml", FileMode.Open))
                {
                    pl = (PatientList)serializer.Deserialize(fs);
                }

                patients = pl.Items.OrderBy(w => w.LastName).OrderBy(w => w.FirstName).ToList();

                RebindPatients();
            }
        }

        #endregion

        #region Support

        /// <summary>
        /// Bind patients to combobox.
        /// </summary>
        private void RebindPatients()
        {
            // Assign to list box
            lbPatients.Items.Clear();
            for (int i = 0; i < patients.Count; i++)
            {
                lbPatients.Items.Add(patients[i].LastName + ", " + patients[i].FirstName);
            }
        }

        /// <summary>
        /// Bind exercises to a dropdown.
        /// </summary>
        public void RebindAssignedExercises()
        {
            if (GlobalVariables.SelectedPatient != null)
            {
                GlobalVariables.SelectedPatient.AssignedExercises = GlobalVariables.SelectedPatient.AssignedExercises.OrderBy(w => w._startDate).OrderBy(w => w._endDate).ToList();

                cbAssignedExercises.Items.Clear();
                for (int i = 0; i < GlobalVariables.SelectedPatient.AssignedExercises.Count; i++)
                {
                    AssignedExercise a = GlobalVariables.SelectedPatient.AssignedExercises[i];

                    // Get the time it was drawn on and made an assignment. can just make a class field.
                    string[] image = a._reason.Split('\\');
                    string parsedDate = image[image.Length - 1].Replace(".png", "");
                    parsedDate = parsedDate.Substring(parsedDate.Length - 15, 15);
                    parsedDate = string.Format("{0}/{1}/{2} {3}:{4}", parsedDate.Substring(0, 4), parsedDate.Substring(4, 2), parsedDate.Substring(6, 2), parsedDate.Substring(9, 2), parsedDate.Substring(11, 2));

                    cbAssignedExercises.Items.Add(string.Format("Assigned {0}, Start {1}, End {2} : {3}", parsedDate, a._startDate.ToString("MM/dd/yyyy"), a._endDate.ToString("MM/dd/yyyy"), a._exerciseName));
                }
            }
            else
            {
                cbAssignedExercises.Items.Clear();
            }
        }

        /// <summary>
        /// Bind exercises to combobox.
        /// </summary>
        public void RebindExercises()
        {
            // Assign to list box
            cbExercise.Items.Clear();
            for (int i = 0; i < GlobalVariables.Exercises.Count; i++)
            {
                cbExercise.Items.Add(GlobalVariables.Exercises[i].Name);
            }
        }

        #endregion

    }
}
